/**
 * @author NORGUET Thibaud
*/
function JS2V_activationUpload(){
    var cmd = "SendMessage 'Level' 'activationUpload' ";
    //alert(cmd);
    document.Virtools.DoCommand(cmd);
}

function JS2V_sendURL(){
    var _url = "http://dev.citu.fr/infinity/images/" + _global_nom;
    var cmd = "SetAttribute '" + _global_nom + "' 'saveURL' '" + _url + "'";
    //alert(cmd);
    document.Virtools.DoCommand(cmd);
    V2JS_Message(_url);
}

function JS2V_sendName(_id){

    var cmd = "SetAttribute '3dFrame_attribute' 'saveName' '" + _global_nom + "'";
    document.Virtools.DoCommand(cmd);
    var cmd = "SetAttribute '3dFrame_attribute' 'saveID' '" + _id + "'";
    document.Virtools.DoCommand(cmd);
    var _url = "http://dev.citu.fr/infinity/images/" + _global_nom;
    var cmd = "SetAttribute '3dFrame_attribute' 'saveURL' '" + _url + "'";
    
    document.Virtools.DoCommand(cmd);
    V2JS_Message(_global_nom);
    
}

function JS2V_uploadSucceed(_nom, _id){
    _global_nom = _nom;
    
    var cmd = "SendMessage 'Level' 'uploadSucceed' ";
    document.Virtools.DoCommand(cmd);
    JS2V_sendName(_id);
}


function JS2V_uploadFailed(){
    var cmd = "SendMessage 'Level' 'uploadFailed' ";
    //alert(cmd);
    document.Virtools.DoCommand(cmd);
}

/* function addslashes(str){
 str = str.replace(/\'/g, '\\\'');
 str = str.replace(/\"/g, '\\"');
 str = str.replace(/\\/g, '\\\\');
 str = str.replace(/\0/g, '\\0');
 return str;
 }*/
function V2JS_Message(_message){
    document.getElementById("upload_message").innerHTML += "Vmessage : " + _message + "<br />";
}

//fonction de sauvegarde des positions d'une image qui viens d'etre mise sur l'environnement virtool
function V2JS_getImagePosition(_position){
    var _tab = _position.split('!');
    
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveImagePosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&id=" + _tab[3] + "&id_user=" + _global_id_user,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}

function JS2V_logout(){
    var cmd = "SendMessage 'Level' 'logout' ";
    document.Virtools.DoCommand(cmd);
}

//fonction appeler toute les x secondes pour avoir les images
function V2JS_currentPosition(_position){

    $.ajax({
        type: "POST",
        url: "./php/getImagePosition.php",
        data: "position=" + _position,
        success: function(){
            var cmd = "SendMessage 'Level' 'written' ";
            document.Virtools.DoCommand(cmd);
        }
    });
}

function V2JS_lastPosition(_position){
    var _tab = _position.split('!');
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveLastPosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&pseudo=" + _global_nom,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}

function JS2V_visiteur(){
	
    var cmd = "SendMessage 'Level' 'visiteur' ";
    document.Virtools.DoCommand(cmd);
    $.ajax({
        type: "POST",
        url: "./php/getPublicImage.php",
    });
   
    
}

function JS2V_login(){
	var cmd = "SendMessage 'Level' 'login' ";
	document.Virtools.DoCommand(cmd);
	
	$.getJSON("./php/getStartPosition.php", {
		"id_user": _global_id_user
	}, function(_json){
	
		var cmd = "SetAttribute '3dFrame_attribute' 'positionCamera' '" + _json['position_cam'] + "'";
		document.Virtools.DoCommand(cmd);
		cmd = "SetAttribute '3dFrame_attribute' 'orientationDir' '" + _json['orientation_dir'] + "'";
		document.Virtools.DoCommand(cmd);
		cmd = "SetAttribute '3dFrame_attribute' 'orientationUp' '" + _json['orientation_up'] + "'";
		document.Virtools.DoCommand(cmd);
		V2JS_Message("pos : " + _json['position_cam']);
		V2JS_Message("orientation_dir : " + _json['orientation_dir']);
		V2JS_Message("orientation_up : " + _json['orientation_up']);
		
	});
	$.getJSON("./php/getUserImage.php", {
		"id_user": _global_id_user
	}, function(_json){
	
		var _html = "";
		for (var _i = 0; _i < _json.length; _i++) {
			var _droit = (_json[_i]['droit'] == "public") ? "disable" : "checked";
			_html += '<div class="image_preview" id="image' + _i + '"><img src="http://chendeb.citu.fr/infinity/imagespreview/' + _json[_i]['nom_image'] + '" alt="' + _json[_i]['nom_image'] + '" onclick="JS2V_uploadSucceed(\'' + _json[_i]['nom_image'] + '\',\'' + _json[_i]['id_image'] + '\')" style="cursor : pointer;" />';
			_html += '<br /><input type="checkbox" id="' + _json[_i]['id_image'] + '" value="' + _json[_i]['id_image'] + '" ' + _droit + ' onmouseup="_changeDroit(' + _json[_i]["id_image"] + ')">';
			_html += '</div>';
			
		}
		
		document.getElementById("preview_image").innerHTML += _html;
		
		
	});
}

function _changeDroit(_id){
    //var _id = $.(_param).attr('id');
    $.ajax({
        type: "POST",
        url: "./php/changeImageDroit.php",
        data: "id_image=" + _id,
    });
}



function ajaxFileUpload(){
    $("#loading").ajaxStart(function(){
        $(this).show();
    }).ajaxComplete(function(){
        $(this).hide();
    });
    
    $.ajaxFileUpload({
        url: './ajaxfileupload/doajaxfileupload.php',
        secureuri: false,
        fileElementId: 'fileToUpload',
        dataType: 'json',
        success: function(data, status){
            if (typeof(data.error) != 'undefined') {
                if (data.error != '') {
                   alert(data.error);
					
                    JS2V_uploadFailed();
                }
                else {
					document.getElementById("fileToUpload").value = "";
                    var _html = "<div class='image_preview'><img src='http://chendeb.citu.fr/infinity/imagespreview/" + data.nom + "' alt='" + data.nom + "' onclick='JS2V_uploadSucceed(\"" + data.nom + "\",\"" + data.id + "\")' style='cursor: pointer;' />";
                    _html += '<br /><input type="checkbox" id="' + data.id + '" value="' + data.id + '" checked onmouseup="_changeDroit(' + data.id + ')">';
                    _html += '</div>';
                    
                    document.getElementById("preview_image").innerHTML += _html;
                }
            }
        },
        error: function(data, status, e){
            alert(e);
        }
    });
    
    return false;
    
}

function _identification(_login){
	$.getJSON("./php/identification.php", {
            "login": _login
        }, function(_json){
			
            if (_json != "") {
                var v_html = "";
               
                document.getElementById('formulaire').style.display = "block";
                _global_id_user = _json['id_user'];
				setTimeout("JS2V_login()", 3000);
				
            }
			else{
				document.getElementById("content").innerHTML += "<br /> Erreur d'identifcation";
			}
            
            
        });
}

function f_admin(x){
    
        if (x == "close") // on ferme la fenetre d'admin
        {
            document.getElementById("admin").style.display = "none";
        }
        else 
            if (x == "pass") //mdp oublié
            {
                var _form = "<form onsubmit='f_sendPassMail(); return false;'>";
                _form += "<fieldset style = 'width: 250px; margin: auto;'> <legend> Oublie de votre pass </legend>";
                _form += "<table><tr><td> Email</td><td> <input type='text' id='email' size='20'></td></tr>";
                _form += "<tr><td colspan='2'><input type='submit' value='Envoyer' ></td></tr>";
                _form += "</table></fieldset></form>";
                $("#contenu_admin").html(_form);
                
            }
            else // premier affichage du module de connexion
            {
                document.getElementById("admin").style.display = "block";
                var _form = "<form onsubmit='f_admin(1); return false;'>";
                _form += "<fieldset style = 'width: 250px; margin: auto;'> <legend> Identification </legend>";
                _form += "<table><tr><td> Login</td><td> <input type='text' id='login' size='15'></td></tr>";
                _form += "<tr><td> pass </td><td><input type='password' id='pass' size='15'></td></tr>";
                _form += "<tr><td><input type='submit' value='Connexion' ></td><td><input type='button' value='Mode visiteur' onclick='JS2V_visiteur(); return false;' ></td></tr>";
                _form += "</table></fieldset></form>";
                _form += "<a href='' onclick='f_nouveau_compte(); return false;'>Créer un compte.</a><br />";
                _form += "<a href='' onclick='f_admin(\"pass\"); return false;'>Mot de pass oublié?</a>";
                
                $("#contenu_admin").html(_form);
            }
}

function f_sendPassMail(){
    var _email = document.getElementById('email').value;
    $.ajax({
        type: "POST",
        url: "./php/sendPassMail.php",
        data: "email=" + _email,
        success: function(_msg){
             document.getElementById('content').innerHTML += "<br />" + _msg;
        }
    });
}

function f_nouveau_compte(){
    var _html = "<fieldset><legend>Création d'un compte.</legend><br /><form onsubmit='f_save_compte(); return false;'>"
    _html += "<table><tr><td> Login</td><td> <input type='text' id='login' size='15' onBlur='f_verif_form(\"login\")'></td></tr>";
    _html += "<tr><td> Pass </td><td><input type='text' id='pass' size='15' onBlur='f_verif_form(\"pass\")'></td></tr>";
    _html += "<tr><td> Adresse mail </td><td><input type='text' id='mail' size='15' onBlur='f_verif_form(\"mail\")'></td></tr>";
    _html += "<tr><td colspan='2'><input type='submit' value='Enregistrer' ></td></tr>";
    _html += "</table></form></fieldset>";
    $("#contenu_admin").html(_html);
}

function f_verif_form(nom_input){

    if (document.getElementById(nom_input).value == "") {
        document.getElementById(nom_input).style.backgroundColor = "#F99";
    }
    else {
        document.getElementById(nom_input).style.backgroundColor = "white";
    }
}

function f_save_compte(){

    var tab = new Array;
    var _login = $("#login").val();
    var _pass = $("#pass").val();
    var _mail = $("#mail").val();
    
    
    if (document.getElementById("login").value == "") {
        tab.push("x");
        document.getElementById("login").style.backgroundColor = "#F99";
    }
    if (document.getElementById("pass").value == "") {
        tab.push("x");
        document.getElementById("pass").style.backgroundColor = "#F99";
    }
    if (document.getElementById("mail").value == "") {
        tab.push("x");
        document.getElementById("mail").style.backgroundColor = "#F99";
    }
    
    if (tab.length == 0) {
        $.ajax({
            type: "POST",
            url: "./php/saveCompte.php",
            data: "login=" + _login + "&pass=" + _pass + "&mail=" + _mail,
            success: function(_msg){
                
                document.getElementById("content").innerHTML += "<br />" + _msg;
            }
        });
    }
    else {
        return false;
        
    }
    
}
